#!/usr/bin/env python3
"""
ESP32串口调试脚本
"""

import serial
import time
import threading

def read_serial(ser):
    """持续读取串口数据"""
    while True:
        try:
            if ser.in_waiting > 0:
                data = ser.read(ser.in_waiting).decode('utf-8', errors='ignore')
                if data.strip():
                    print(f"收到: {repr(data)}")
        except Exception as e:
            print(f"读取错误: {e}")
            break
        time.sleep(0.1)

def main():
    try:
        print("=== ESP32串口调试 ===")
        print("连接到/dev/ttyUSB0...")
        
        # 打开串口
        ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        time.sleep(2)
        
        # 启动读取线程
        read_thread = threading.Thread(target=read_serial, args=(ser,), daemon=True)
        read_thread.start()
        
        print("串口已连接，开始测试...")
        print("输入命令 (输入'quit'退出):")
        
        # 先发送一些测试命令
        test_commands = ["PING", "INFO", "SET:LED:ON", "SET:LED:OFF"]
        
        for cmd in test_commands:
            print(f"\n发送: {cmd}")
            ser.write(f"{cmd}\n".encode())
            time.sleep(1)
        
        # 交互模式
        while True:
            try:
                cmd = input("\n输入命令: ").strip()
                if cmd.lower() == 'quit':
                    break
                if cmd:
                    ser.write(f"{cmd}\n".encode())
                    time.sleep(0.5)
            except KeyboardInterrupt:
                break
        
        ser.close()
        print("串口已关闭")
        
    except Exception as e:
        print(f"错误: {e}")

if __name__ == "__main__":
    main()